package com.quasar.hpatient.view;

import android.annotation.TargetApi;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.util.SparseArray;
import android.widget.Toast;

import com.hyphenate.EMCallBack;
import com.hyphenate.EMContactListener;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMCmdMessageBody;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.easeui.utils.EaseCommonUtils;
import com.hyphenate.exceptions.HyphenateException;
import com.hyphenate.util.EMLog;
import com.quasar.hpatient.MainAppliaction;
import com.quasar.hpatient.R;
import com.quasar.hpatient.base.BaseActivity;
import com.quasar.hpatient.constant.ConstantManger;
import com.quasar.hpatient.model.custommodel.InspactionBean;
import com.quasar.hpatient.model.event.CloseEvent;
import com.quasar.hpatient.model.httpmodel.AnotherResult;
import com.quasar.hpatient.model.httpmodel.DataStateResult;
import com.quasar.hpatient.model.httpmodel.OuterLayerDataResult;
import com.quasar.hpatient.model.medicalmodel.BaseInfoVersionData;
import com.quasar.hpatient.model.medicalmodel.PatientInfoData;
import com.quasar.hpatient.model.medicalmodel.UpdateEdition;
import com.quasar.hpatient.network.RetrofitConnection;
import com.quasar.hpatient.onInterface.AnotherResultListener;
import com.quasar.hpatient.onInterface.ExternalRecordsListener;
import com.quasar.hpatient.onInterface.OnInfoVersionListener;
import com.quasar.hpatient.presenter.BaseInfoVersionPresenter;
import com.quasar.hpatient.presenter.ExternalRecordsPresenter;
import com.quasar.hpatient.presenter.TestRecordPresenter;
import com.quasar.hpatient.step.service.StepService;
import com.quasar.hpatient.utils.SystemTool;
import com.quasar.hpatient.utils.runtimepermissions.PermissionsManager;
import com.quasar.hpatient.utils.runtimepermissions.PermissionsResultAction;
import com.quasar.hpatient.view.personal.setup.UpAppActivity_;
import com.quasar.hpatient.widget.NaviTabButton;
import com.vise.log.ViseLog;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.ViewById;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.util.List;
import java.util.Random;
import java.util.Set;

import chatui.Constant;
import chatui.DemoHelper;
import chatui.cacha.UserCacheManager;
import chatui.db.DemoDBManager;
import chatui.db.InviteMessgeDao;
import chatui.ui.ChatActivity;
import chatui.ui.GroupsActivity;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import me.leolin.shortcutbadger.ShortcutBadger;

@EActivity(R.layout.activity_main)
public class MainActivity extends BaseActivity implements NaviTabButton.OnSelect,ExternalRecordsListener,
        OnInfoVersionListener{

    PatientInfoData patient = MainAppliaction.getInstance().getPatient();
    //更新数据信息
    private BaseInfoVersionPresenter baseInfoVersionPresenter;


    private Fragment[] mFragments;
    private NaviTabButton[] mTabButtons;
    int exitNum;
    //环信
    private InviteMessgeDao inviteMessgeDao;
    private LocalBroadcastManager broadcastManager;
    private BroadcastReceiver broadcastReceiver;
    private BroadcastReceiver internalDebugReceiver;
    private boolean isExceptionDialogShow = false;
    public boolean isConflict = false;
    private AlertDialog.Builder exceptionBuilder;
    private boolean isCurrentAccountRemoved = false;

    @ViewById(R.id.tabbutton_chat)
    NaviTabButton tabbutton_chat;
    @ViewById(R.id.tabbutton_contact)
    NaviTabButton tabbutton_contact;
    @ViewById(R.id.tabbutton_internal)
    NaviTabButton tabbutton_internal;
    @ViewById(R.id.tabbutton_my)
    NaviTabButton tabbutton_my;

    @Extra
    String Viewid;

    @Extra
    String VisitView;
    ExternalRecordsPresenter externalRecordsPresenter;

    //设置标题文字
    public static SparseArray<String> titles = new SparseArray<>();

    static {
        titles.put(0, "首页");
        titles.put(1, "我的医生");
        titles.put(2, "社区");
        titles.put(3, "个人中心");
    }


    public void setFragmentIndicator(int which) {
        //操作其他按钮时exitNum默认置位0
        exitNum = 0;
        getSupportFragmentManager().beginTransaction().hide(mFragments[0])
                .hide(mFragments[1]).hide(mFragments[2]).hide(mFragments[3])
                .show(mFragments[which]).commit();

        mTabButtons[0].setSelectedButton(false);
        mTabButtons[1].setSelectedButton(false);
        mTabButtons[2].setSelectedButton(false);
        mTabButtons[3].setSelectedButton(false);
        mTabButtons[which].setSelectedButton(true);
    }

    private void initFragment() {
        mFragments = new Fragment[4];

        mFragments[0] = getSupportFragmentManager().findFragmentById(
                R.id.hoFragment);
        mFragments[1] = getSupportFragmentManager().findFragmentById(
                R.id.doctorFragment);
        mFragments[2] = getSupportFragmentManager().findFragmentById(
                R.id.communityFragment);
        mFragments[3] = getSupportFragmentManager().findFragmentById(
                R.id.myFragment);
    }

    @AfterViews
    void init() {
        if (!DemoHelper.getInstance().isLoggedIn()) {
            logChat(patient, patient.getBmobUserName());
        }
        initTab();
        initFragment();
        setFragmentIndicator(0);
        initView();
        initData();

        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

        chat();

        PostEdition();

        //登陆极光推送
        PushInterface();
        Intent intent = new Intent(this, StepService.class);
        startService(intent);
    }


    private void initTab() {
        mTabButtons = new NaviTabButton[4];

        mTabButtons[0] = tabbutton_chat;
        mTabButtons[1] = tabbutton_contact;
        mTabButtons[2] = tabbutton_internal;
        mTabButtons[3] = tabbutton_my;

        mTabButtons[0].setTitle("首页");
        mTabButtons[0].setIndex(0);
        mTabButtons[0].setSelectedImage(getResources().getDrawable(
                R.mipmap.ic_home_1));
        mTabButtons[0].setUnselectedImage(getResources().getDrawable(
                R.mipmap.ic_home));

        mTabButtons[1].setTitle("我的医生");
        mTabButtons[1].setIndex(1);
        mTabButtons[1].setSelectedImage(getResources().getDrawable(
                R.mipmap.ic_doctor_1));
        mTabButtons[1].setUnselectedImage(getResources().getDrawable(
                R.mipmap.ic_doctor));

        mTabButtons[2].setTitle("发现");
        mTabButtons[2].setIndex(2);
        mTabButtons[2].setSelectedImage(getResources().getDrawable(
                R.mipmap.ic_comm_1));
        mTabButtons[2].setUnselectedImage(getResources().getDrawable(
                R.mipmap.ic_comm));
        mTabButtons[3].setTitle("我");
        mTabButtons[3].setIndex(3);
        mTabButtons[3].setSelectedImage(getResources().getDrawable(
                R.mipmap.ic_my_1));
        mTabButtons[3].setUnselectedImage(getResources().getDrawable(
                R.mipmap.ic_my));

        for (NaviTabButton bt : mTabButtons) {
            bt.setOnSelect(this);
        }
    }

    @Override
    public void select(int index) {
        setFragmentIndicator(index);
    }

    @Override
    protected void initView() {
    }

    @Override
    protected void initData() {
        requestPermissions();
        externalRecordsPresenter=new ExternalRecordsPresenter(this);
//        testRecordPresenter=new TestRecordPresenter(this);
        baseInfoVersionPresenter=new BaseInfoVersionPresenter(this);
        baseInfoVersionPresenter.seleteTableName();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);

        if (exceptionBuilder != null) {
            exceptionBuilder.create().dismiss();
            exceptionBuilder = null;
            isExceptionDialogShow = false;
        }
        unregisterBroadcastReceiver();

        try {
            unregisterReceiver(internalDebugReceiver);
        } catch (Exception e) {
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(CloseEvent closeEvent) {
        finish();
    }

    @Override
    public void onBackPressed() {
        if (exitNum < 1) {
            exitNum++;
            Toast.makeText(this, "再按一次返回键退出程序", Toast.LENGTH_SHORT).show();
        } else {
            finish();
        }
    }

    //判断23以上的动态申请权限
    @TargetApi(23)
    private void requestPermissions() {
        PermissionsManager.getInstance().requestAllManifestPermissionsIfNecessary(this, new PermissionsResultAction() {
            @Override
            public void onGranted() {
//				Toast.makeText(MainActivity.this, "All permissions have been granted", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onDenied(String permission) {
                //Toast.makeText(MainActivity.this, "Permission " + permission + " has been denied", Toast.LENGTH_SHORT).show();
            }
        });
    }

    //权限借口回调
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        PermissionsManager.getInstance().notifyPermissionsChange(permissions, grantResults);
    }

    /**
     * 环信
     */
    public void chat() {
        showExceptionDialogFromIntent(getIntent());
        inviteMessgeDao = new InviteMessgeDao(this);
        registerBroadcastReceiver();
        EMClient.getInstance().contactManager().setContactListener(new MyContactListener());
        registerInternalDebugReceiver();
    }

    private void registerInternalDebugReceiver() {
        internalDebugReceiver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                DemoHelper.getInstance().logout(false, new EMCallBack() {

                    @Override
                    public void onSuccess() {
                        runOnUiThread(new Runnable() {
                            public void run() {
                                finish();
                                startActivity(new Intent(MainActivity.this, LoginActivity.class));
                            }
                        });
                    }

                    @Override
                    public void onProgress(int progress, String status) {
                    }

                    @Override
                    public void onError(int code, String message) {
                    }
                });
            }
        };
        IntentFilter filter = new IntentFilter(getPackageName() + ".em_internal_debug");
        registerReceiver(internalDebugReceiver, filter);
    }


    public class MyContactListener implements EMContactListener {
        @Override
        public void onContactAdded(String username) {
        }

        @Override
        public void onContactDeleted(final String username) {
            runOnUiThread(new Runnable() {
                public void run() {
                    if (ChatActivity.activityInstance != null && ChatActivity.activityInstance.toChatUsername != null &&
                            username.equals(ChatActivity.activityInstance.toChatUsername)) {
                        String st10 = getResources().getString(R.string.have_you_removed);
                        Toast.makeText(MainActivity.this, ChatActivity.activityInstance.getToChatUsername() + st10, Toast.LENGTH_LONG)
                                .show();
                        ChatActivity.activityInstance.finish();
                    }
                }
            });
            updateUnreadAddressLable();
        }

        @Override
        public void onContactInvited(String username, String reason) {
        }

        @Override
        public void onFriendRequestAccepted(String username) {
        }

        @Override
        public void onFriendRequestDeclined(String username) {
        }
    }

    /**
     * update the total unread count
     */
    public void updateUnreadAddressLable() {
        runOnUiThread(new Runnable() {
            public void run() {
                int count = getUnreadAddressCountTotal();
                if (count > 0) {
                    //红点消息数量
                    //unreadAddressLable.setVisibility(View.VISIBLE);
                } else {
                    //unreadAddressLable.setVisibility(View.INVISIBLE);
                }
            }
        });

    }

    /**
     * 消息数量
     * update unread message count
     */
    public void updateUnreadLabel() {
        int count = getUnreadMsgCountTotal();
        tabbutton_my.setUnreadNotify(count);
        ShortcutBadger.applyCount(MainActivity.this, count); //for 1.1.4+
    }

    /**
     * get unread message count
     *
     * @return
     */

    public int getUnreadMsgCountTotal() {
        int unreadMsgCountTotal = 0;
        int chatroomUnreadMsgCount = 0;
        unreadMsgCountTotal = EMClient.getInstance().chatManager().getUnreadMessageCount();
        for (EMConversation conversation : EMClient.getInstance().chatManager().getAllConversations().values()) {
            if (conversation.getType() == EMConversation.EMConversationType.ChatRoom)
                chatroomUnreadMsgCount = chatroomUnreadMsgCount + conversation.getUnreadMsgCount();
        }
        return unreadMsgCountTotal - chatroomUnreadMsgCount;
    }


    /**
     * get unread event notification count, including application, accepted, etc
     *
     * @return
     */
    public int getUnreadAddressCountTotal() {
        int unreadAddressCountTotal = 0;
        unreadAddressCountTotal = inviteMessgeDao.getUnreadMessagesCount();
        return unreadAddressCountTotal;
    }

    private void unregisterBroadcastReceiver() {
        broadcastManager.unregisterReceiver(broadcastReceiver);
    }


    private void showExceptionDialogFromIntent(Intent intent) {
        EMLog.e("dialog", "showExceptionDialogFromIntent");
        if (!isExceptionDialogShow && intent.getBooleanExtra(Constant.ACCOUNT_CONFLICT, false)) {
            showExceptionDialog(Constant.ACCOUNT_CONFLICT);
        } else if (!isExceptionDialogShow && intent.getBooleanExtra(Constant.ACCOUNT_REMOVED, false)) {
            showExceptionDialog(Constant.ACCOUNT_REMOVED);
        } else if (!isExceptionDialogShow && intent.getBooleanExtra(Constant.ACCOUNT_FORBIDDEN, false)) {
            showExceptionDialog(Constant.ACCOUNT_FORBIDDEN);
        }
    }


    /**
     * show the dialog when user met some exception: such as login on another device, user removed or user forbidden
     */
    private void showExceptionDialog(String exceptionType) {
        isExceptionDialogShow = true;
        DemoHelper.getInstance().logout(false, null);
        String st = getResources().getString(R.string.Logoff_notification);
        if (!MainActivity.this.isFinishing()) {
            // clear up global variables
            try {
                if (exceptionBuilder == null)
                    exceptionBuilder = new AlertDialog.Builder(MainActivity.this);
                exceptionBuilder.setTitle(st);
                exceptionBuilder.setMessage(getExceptionMessageId(exceptionType));
                exceptionBuilder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        exceptionBuilder = null;
                        isExceptionDialogShow = false;

                        DemoHelper.getInstance().logout(false, new EMCallBack() {
                            @Override
                            public void onSuccess() {
                                runOnUiThread(new Runnable() {
                                    public void run() {
                                        finish();
                                        Intent intent = new Intent(MainActivity.this, LoginActivity_.class);
                                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                                        startActivity(intent);
                                    }
                                });
                            }

                            @Override
                            public void onProgress(int progress, String status) {

                            }

                            @Override
                            public void onError(int code, String message) {
                                runOnUiThread(new Runnable() {

                                    @Override
                                    public void run() {
                                        // TODO Auto-generated method stub
//                                        Toast.makeText(SettingActivity.this, "unbind devicetokens failed", Toast.LENGTH_SHORT).show();
                                    }
                                });
                            }
                        });

                    }
                });
                exceptionBuilder.setCancelable(false);
                exceptionBuilder.create().show();
                isConflict = true;
            } catch (Exception e) {
                EMLog.e("Exception", "---------color conflictBuilder error" + e.getMessage());
            }
        }
    }

    private int getExceptionMessageId(String exceptionType) {
        if (exceptionType.equals(Constant.ACCOUNT_CONFLICT)) {
            return R.string.connect_conflict;
        } else if (exceptionType.equals(Constant.ACCOUNT_REMOVED)) {
            return R.string.em_user_remove;
        } else if (exceptionType.equals(Constant.ACCOUNT_FORBIDDEN)) {
            return R.string.user_forbidden;
        }
        return R.string.Network_error;
    }

    private void registerBroadcastReceiver() {
        broadcastManager = LocalBroadcastManager.getInstance(this);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constant.ACTION_CONTACT_CHANAGED);
        intentFilter.addAction(Constant.ACTION_GROUP_CHANAGED);
        // intentFilter.addAction(RPConstant.REFRESH_GROUP_RED_PACKET_ACTION);*/
        broadcastReceiver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                updateUnreadLabel();
                updateUnreadAddressLable();

                //刷新fragment
                String action = intent.getAction();
                if (action.equals(Constant.ACTION_GROUP_CHANAGED)) {
                    if (EaseCommonUtils.getTopActivity(MainActivity.this).equals(GroupsActivity.class.getName())) {
                        GroupsActivity.instance.onResume();
                    }
                }
            }
        };
        broadcastManager.registerReceiver(broadcastReceiver, intentFilter);
    }

    @Override
    protected void onResume() {
        super.onResume();

        exitNum = 0;

        if (Viewid != null) {
            setFragmentIndicator(Integer.parseInt(Viewid));
        }

        Viewid = null;

        if (!isConflict && !isCurrentAccountRemoved) {
            updateUnreadLabel();
            updateUnreadAddressLable();
        }

        // unregister this event listener when this activity enters the
        // background
        DemoHelper sdkHelper = DemoHelper.getInstance();
        sdkHelper.pushActivity(this);

        EMClient.getInstance().chatManager().addMessageListener(messageListener);

        //点击来院复诊推送消息后跳转main弹出dialog消息提示
        if (VisitView != null && VisitView.length() > 0) {
            android.app.AlertDialog.Builder dialog = new android.app.AlertDialog.Builder(MainActivity_.intent(this).getContext());
            dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                }
            }).setMessage("请于" + VisitView + "来院复诊").show();
        }

        VisitView = null;

    }

    private void refreshUIWithMessage() {
        runOnUiThread(new Runnable() {
            public void run() {
                // refresh unread count
                updateUnreadLabel();
            }
        });
    }

    EMMessageListener messageListener = new EMMessageListener() {

        @Override
        public void onMessageReceived(List<EMMessage> messages) {
            // notify new message
            for (EMMessage message : messages) {
                DemoHelper.getInstance().getNotifier().onNewMsg(message);
            }
            refreshUIWithMessage();
        }

        @Override
        public void onCmdMessageReceived(List<EMMessage> messages) {
            //red packet code : 处理红包回执透传消息
            for (EMMessage message : messages) {
                EMCmdMessageBody cmdMsgBody = (EMCmdMessageBody) message.getBody();
                final String action = cmdMsgBody.action();//获取自定义action
               /* if (action.equals(RPConstant.REFRESH_GROUP_RED_PACKET_ACTION)) {
                    RedPacketUtil.receiveRedPacketAckMessage(message);
                }*/
            }
            //end of red packet code
            refreshUIWithMessage();
        }

        @Override
        public void onMessageRead(List<EMMessage> messages) {
        }

        @Override
        public void onMessageDelivered(List<EMMessage> message) {
        }

        @Override
        public void onMessageChanged(EMMessage message, Object change) {
        }

    };

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        showExceptionDialogFromIntent(intent);
    }


    /**
     * //极光登陆
     * PushInterface(patientInfoBean.getData());
     * 极光推送登陆
     */

    public void PushInterface() {
        JPushInterface.setAliasAndTags(this,
                patient.getBmobUserName(),
                null,
                mAliasCallback);
    }

    private static final String TAG = "JPush";

    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {
        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    Log.i(TAG, logs);

                    // 建议这里往 SharePreference 里写一个成功设置的状态。成功设置一次后，以后不必再次设置了。

                    break;
                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    Log.i(TAG, logs);
                    // 延迟 60 秒来调用 Handler 设置别名
                    mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS, alias), 1000 * 60);
                    break;
                default:
                    logs = "Failed with errorCode = " + code;
                    Log.e(TAG, logs);
            }
        }
    };

    private static final int MSG_SET_ALIAS = 1001;
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_SET_ALIAS:
//                    Log.d(TAG, "Set alias in handler.");
                    // 调用 JPush 接口来设置别名。
                    JPushInterface.setAliasAndTags(MainActivity.this,
                            patient.getBmobUserName(),
                            null,
                            mAliasCallback);
                    break;
                default:
//                    Log.i(TAG, "Unhandled msg - " + msg.what);
            }
        }
    };

    //检测版本请求
    public void PostEdition() {
        ViseLog.d("enter");
        RetrofitConnection.getBasicDataUrls().UpApp(ConstantManger.userType)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<OuterLayerDataResult<UpdateEdition>>() {
                    @Override
                    public void onSubscribe(@io.reactivex.annotations.NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@io.reactivex.annotations.NonNull OuterLayerDataResult<UpdateEdition> updateEditionOuterLayerDataResult) {

                        if (updateEditionOuterLayerDataResult.getData() != null) {
                            if (updateEditionOuterLayerDataResult.getData().getVersion() != null &&
                                    updateEditionOuterLayerDataResult.getData().getVersion().length() > 0) {
                                //网络最新的apk版本信息
                                int PostVersion = Integer.parseInt(updateEditionOuterLayerDataResult.getData().getVersion());
                                //当前apk的版本号
                                int version = SystemTool.getAppVersionCode(MainActivity.this);
                                if (PostVersion > version) {
                                    dialogEdition(updateEditionOuterLayerDataResult.getData());
                                }
                            }
                        }
                    }

                    @Override
                    public void onError(@io.reactivex.annotations.NonNull Throwable e) {

                        ViseLog.d(TAG, "onError: " + e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }

    //如果有新版本进行提示
    public void dialogEdition(final UpdateEdition updata) {
        final AlertDialog.Builder normalDialog =
                new AlertDialog.Builder(this);
        normalDialog.setTitle("版本升级提醒");
        normalDialog.setMessage("当前有新版本是否升级?");
        normalDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //...To-do
                        UpAppActivity_.intent(MainActivity.this).updateEdition(updata).start();
                    }
                });
        normalDialog.setNegativeButton("关闭",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //...To-do

                    }
                });
        // 显示
        normalDialog.show();

    }


    /**
     * 登陆环信
     *
     * @param userName 账号   密码默认为 123456
     */
    public void logChat(final PatientInfoData patientInfoData, final String userName) {
        // After logout，the DemoDB may still be accessed due to async callback, so the DemoDB will be re-opened again.
        // close it before login to make sure DemoDB not overlap
        EMClient.getInstance().logout(true); //登陆前先退出，保证登陆成功！
        DemoDBManager.getInstance().closeDB();

        // reset current user name before login
        DemoHelper.getInstance().setCurrentUserName(userName);
        EMClient.getInstance().login(userName, "a123456", new EMCallBack() {

            @Override
            public void onSuccess() {

                Random random = new Random();
                // 登录成功，将用户的昵称头像缓存在本地
                String userId = EMClient.getInstance().getCurrentUser();// 用户环信ID
                //名称
                String nickName;
                if (patientInfoData.getRealName() != null) {
                    nickName = patientInfoData.getRealName();
                } else {
                    nickName = userName;
                }

                String avatarUrl = "";
                if (patientInfoData.getCover() != null) {
                    avatarUrl = RetrofitConnection.PHOTOURL + patientInfoData.getCover();
                }


                UserCacheManager.save(userId, nickName, avatarUrl);

                // ** manually load all local groups and conversation
                EMClient.getInstance().groupManager().loadAllGroups();
                EMClient.getInstance().chatManager().loadAllConversations();

                String nick = "";
                try {
                    nick = EMClient.getInstance().pushManager().getPushConfigsFromServer().getDisplayNickname();
                } catch (HyphenateException e) {
                    e.printStackTrace();
                }

                // update current user's display name for APNs
                boolean updatenick = EMClient.getInstance().pushManager().updatePushNickname(nickName);
                if (!updatenick) {
                    Log.e("LoginActivity", "update current user nick fail");
                }

                DemoHelper.getInstance().getUserProfileManager().asyncGetCurrentUserInfo();
            }

            @Override
            public void onProgress(int progress, String status) {
                ViseLog.d("login: onProgress" + status);
            }

            @Override
            public void onError(final int code, final String message) {
                //登陆环信失败跳转到登陆界面
                ViseLog.d("login: onError:" + code + "+++" + message);
                EventBus.getDefault().post(new CloseEvent());
                LoginActivity_.intent(MainActivity.this).start();
            }
        });

    }

    @Override
    public void onExternalRecordsSuccess(DataStateResult data) {

    }

    @Override
    public void onExternalRecordsError(String msg) {

    }

    @Override
    public void onExternalRecordsRefreshUI() {

    }




    @Override
    public void onInfoVersionDataSuccess(AnotherResult<BaseInfoVersionData> data) {

    }

    @Override
    public void onInfoVersionError(String msg) {

    }

    @Override
    public void onInfoVersionRefreshUI() {

    }

    @Override
    public void onInfoVersionUpdateSuccess() {

    }
}